package com.jcl.dd.aspect;

import com.jcl.dd.annotation.DataSource;
import com.jcl.dd.datasource.DynamicDataSourceHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class DataSourceAspect {

    @Pointcut("@annotation(com.jcl.dd.annotation.DataSource) || @within(com.jcl.dd.annotation.DataSource)")
    public void dd() {

    }

    @Around("dd()")
    public Object around(ProceedingJoinPoint pj) {
        DataSource dataSource = getDataSource(pj);
        if (dataSource != null) {
            //获取数据源名称
            String value = dataSource.value();
            DynamicDataSourceHolder.setDataSourceType(value);
            try {
                return pj.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            } finally {
                DynamicDataSourceHolder.clear();
            }
        }
        return null;
    }

    public DataSource getDataSource(ProceedingJoinPoint pj) {
        MethodSignature signature = (MethodSignature) pj.getSignature();
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (dataSource != null) {
            return dataSource;
        }
        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
    }
}
